﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using YArchitech.MEP.Electric.Common;
using libxl;

namespace YArchitech.MEP.Electric.CableLay
{
	public partial class CableListImportForm : System.Windows.Forms.Form
	{
		public CableListImportForm(List<CableListField> fields)
		{
			this.InitializeComponent();
			this.m_fields = fields;
			IList<string> list = new string[]
			{
				"A",
				"B",
				"C",
				"D",
				"E",
				"F",
				"G",
				"H",
				"I",
				"J",
				"K",
				"L",
				"M",
				"N",
				"O",
				"P",
				"Q",
				"R",
				"S",
				"T",
				"U",
				"V",
				"W",
				"X",
				"Y",
				"Z"
			};
			for (int i = 0; i < fields.Count; i++)
			{
				DataGridViewRow dataGridViewRow = new DataGridViewRow();
				DataGridViewTextBoxCell dataGridViewTextBoxCell = new DataGridViewTextBoxCell();
				if (string.IsNullOrWhiteSpace(fields[i].Title))
				{
					dataGridViewTextBoxCell.Value = fields[i].Name;
				}
				else
				{
					dataGridViewTextBoxCell.Value = fields[i].Title;
				}
				dataGridViewRow.Cells.Add(dataGridViewTextBoxCell);
				DataGridViewTextBoxCell dataGridViewTextBoxCell2 = new DataGridViewTextBoxCell();
				dataGridViewTextBoxCell2.Value = list[i];
				dataGridViewRow.Cells.Add(dataGridViewTextBoxCell2);
				this.dataGridView.Rows.Add(dataGridViewRow);
			}
			this.ReadFormDataFromXml();
			this.m_cmbSelectValue.DropDownStyle = ComboBoxStyle.DropDownList;
			this.m_cmbSelectValue.Click += this.cmbSelectValue_Click;
			this.m_cmbSelectValue.Leave += this.cmbSelectValue_Leave;
			this.m_cmbSelectValue.Items.AddRange(list.ToArray<string>());
			this.m_cmbSelectValue.Visible = false;
			this.dataGridView.Controls.Add(this.m_cmbSelectValue);
		}

		private void cmbSelectValue_Click(object sender, EventArgs e)
		{
			if (1 != this.dataGridView.SelectedRows.Count)
			{
				foreach (object obj in this.dataGridView.SelectedRows)
				{
					DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
					this.dataGridView.Rows[dataGridViewRow.Index].Selected = false;
				}
				this.dataGridView.Rows[this.m_rowIndex].Selected = true;
				this.dataGridView.CurrentCell = this.dataGridView.Rows[this.m_rowIndex].Cells[this.m_columnIndex];
			}
		}

		private void cmbSelectValue_Leave(object sender, EventArgs e)
		{
			this.dataGridView.CurrentCell.Value = ((ComboBox)sender).Text;
			((ComboBox)sender).Visible = false;
		}

		private void btnBrowse_Click(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();
			openFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";
			if (Directory.Exists(this.tbExcelPath.Text.Trim()))
			{
				openFileDialog.InitialDirectory = this.tbExcelPath.Text.Trim();
			}
			else
			{
				string text = this.tbExcelPath.Text.Trim();
				int length = text.LastIndexOf("\\");
				string initialDirectory = text.Substring(0, length);
				openFileDialog.InitialDirectory = initialDirectory;
			}
			if (openFileDialog.ShowDialog(this) == DialogResult.OK)
			{
				this.m_excelBook = new XmlBook();
				this.m_excelBook.setKey("Beijing YArchitech Tongxing Technology Co.,Ltd", "windows-282b2c0f08cbe70966b4616ea0i8d7n0");
				try
				{
					this.m_excelBook.load(openFileDialog.FileName);
				}
				catch (System.Exception ex)
				{
					if ("libxl: Permission denied." == ex.Message)
					{
						this.m_excelBook = null;
						MessageBox.Show("检测到此Excel文件已在外部打开，请先关闭，再重新操作。", "盈建科提示");
						return;
					}
				}
				this.tbExcelPath.Text = openFileDialog.FileName;
				this.clbCableCaterory.Items.Clear();
				int num = this.m_excelBook.sheetCount();
				for (int i = 0; i < num; i++)
				{
					Sheet sheet = this.m_excelBook.getSheet(i);
					this.clbCableCaterory.Items.Add(sheet.name);
				}
				if (num > 0)
				{
					this.clbCableCaterory.SetItemChecked(0, true);
				}
			}
		}

		private void CableListImportForm_Load(object sender, EventArgs e)
		{
			base.Icon = Resource.YArchitechIcon;
		}

		private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0 || e.RowIndex >= this.dataGridView.Rows.Count)
			{
				return;
			}
			this.m_rowIndex = e.RowIndex;
			this.m_columnIndex = e.ColumnIndex;
			if (1 == e.ColumnIndex)
			{
				if (this.dataGridView.CurrentCell.Value != null)
				{
					this.m_cmbSelectValue.Text = this.dataGridView.CurrentCell.Value.ToString();
				}
				Rectangle cellDisplayRectangle = this.dataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
				this.m_cmbSelectValue.Left = cellDisplayRectangle.Left;
				this.m_cmbSelectValue.Top = cellDisplayRectangle.Top;
				this.m_cmbSelectValue.Width = cellDisplayRectangle.Width;
				this.m_cmbSelectValue.Height = cellDisplayRectangle.Height;
				this.m_cmbSelectValue.Visible = true;
				return;
			}
			this.m_cmbSelectValue.Visible = false;
		}

		private void btnImport_Click(object sender, EventArgs e)
		{
			if (this.clbCableCaterory.Items.Count == 0)
			{
				return;
			}
			this.SaveFormDataToXml();
			int num = int.Parse(this.tbStartRow.Text) - 1;
			try
			{
				int lengthCol = -1;
				int layPathCol = -1;
				for (int i = 0; i < this.dataGridView.RowCount; i++)
				{
					string alphabet = this.dataGridView.Rows[i].Cells[1].Value.ToString();
					if ("Length" == this.m_fields[i].DbName)
					{
						lengthCol = this.ConvertAlphabetToInt(alphabet);
					}
					else if ("LayPath" == this.m_fields[i].DbName)
					{
						layPathCol = this.ConvertAlphabetToInt(alphabet);
					}
				}
				List<ExcelRecord> list = new List<ExcelRecord>();
				for (int j = 0; j < this.clbCableCaterory.Items.Count; j++)
				{
					if (this.clbCableCaterory.GetItemChecked(j))
					{
						ExcelRecord excelRecord = new ExcelRecord();
						excelRecord.sheetIndex = j;
						Sheet sheet = this.m_excelBook.getSheet(j);
						excelRecord.sheetName = sheet.name;
						excelRecord.lengthCol = lengthCol;
						excelRecord.layPathCol = layPathCol;
						excelRecord.excelPath = this.tbExcelPath.Text;
						list.Add(excelRecord);
					}
				}
				CableLayDatabase.ThisDb.SaveCableDatasToDb(list);
				int num2 = 0;
				this.m_cableListData = new List<CableListData>();
				for (int k = 0; k < this.clbCableCaterory.Items.Count; k++)
				{
					if (this.clbCableCaterory.GetItemChecked(k))
					{
						Sheet sheet2 = this.m_excelBook.getSheet(k);
						for (int l = num; l < sheet2.lastRow(); l++)
						{
							CableListData cableListData = new CableListData();
							for (int m = 0; m < this.dataGridView.RowCount; m++)
							{
								string alphabet2 = this.dataGridView.Rows[m].Cells[1].Value.ToString();
								int col = this.ConvertAlphabetToInt(alphabet2);
								string text = this.ReadExcelCell(sheet2, l, col);
								if (!(text == string.Empty))
								{
									if ("CableNum" == this.m_fields[m].DbName)
									{
										cableListData.CableNum = text;
									}
									else if ("StartNum" == this.m_fields[m].DbName)
									{
										cableListData.StartNum = text;
									}
									else if ("EndNum" == this.m_fields[m].DbName)
									{
										cableListData.EndNum = text;
									}
									else if ("CableModel" == this.m_fields[m].DbName)
									{
										cableListData.CableModel = text;
									}
									else if ("CableSpec" == this.m_fields[m].DbName)
									{
										cableListData.CableSpec = text;
									}
									else if ("Length" == this.m_fields[m].DbName)
									{
										cableListData.Length = text;
									}
									else if ("LayPath" == this.m_fields[m].DbName)
									{
										cableListData.LayPath = text;
									}
									else if ("Remark" == this.m_fields[m].DbName)
									{
										cableListData.Remark = text;
									}
									cableListData.SheetID = list[num2].id;
									cableListData.Row = l;
								}
							}
							this.m_cableListData.Add(cableListData);
						}
						num2++;
					}
				}
			}
			catch (System.Exception)
			{
				MessageBox.Show("导入电缆清册失败。", "盈建科提示");
			}
		}

		private void ReadFormDataFromXml()
		{
			YArchitech.MEP.Electric.Common.XmlHelper xmlHelper = new YArchitech.MEP.Electric.Common.XmlHelper(CableLayCommon.GetUserDataFile(), "ElectricData");
			xmlHelper.SelectNode("CableListImportForm");
			string text = Path.Combine(Product.InstallLocation, "UserWork");
			string attributeEx = xmlHelper.GetAttributeEx("ExcelPath", text);
			this.tbExcelPath.Text = (string.IsNullOrWhiteSpace(attributeEx) ? text : attributeEx);
			if (File.Exists(this.tbExcelPath.Text))
			{
				if (this.m_excelBook == null)
				{
					this.m_excelBook = new XmlBook();
					this.m_excelBook.setKey("Beijing YArchitech Tongxing Technology Co.,Ltd", "windows-282b2c0f08cbe70966b4616ea0i8d7n0");
					try
					{
						this.m_excelBook.load(this.tbExcelPath.Text);
					}
					catch (System.Exception ex)
					{
						if ("libxl: Permission denied." == ex.Message)
						{
							this.m_excelBook = null;
							MessageBox.Show("检测到此Excel文件已在外部打开，请先关闭，再重新操作。", "盈建科提示");
						}
					}
				}
				if (this.m_excelBook != null)
				{
					int num = this.m_excelBook.sheetCount();
					for (int i = 0; i < num; i++)
					{
						Sheet sheet = this.m_excelBook.getSheet(i);
						this.clbCableCaterory.Items.Add(sheet.name);
					}
					attributeEx = xmlHelper.GetAttributeEx("SheetName", "0");
					char[] separator = new char[]
					{
						','
					};
					foreach (string text2 in attributeEx.Split(separator))
					{
						if (!(string.Empty == text2))
						{
							int index = int.Parse(text2);
							this.clbCableCaterory.SetItemChecked(index, true);
						}
					}
				}
			}
			attributeEx = xmlHelper.GetAttributeEx("StartRow", "2");
			this.tbStartRow.Text = attributeEx;
			this.m_addDataMode = (AddDataMode)int.Parse(xmlHelper.GetAttributeEx("Type", "0"));
			if (this.m_addDataMode == AddDataMode.Add_Ignore)
			{
				this.rbAdd.Checked = true;
			}
			else if (AddDataMode.Add_Overwrite == this.m_addDataMode)
			{
				this.rbCover.Checked = true;
			}
			else if (AddDataMode.Add_SameRetain == this.m_addDataMode)
			{
				this.rbKeep.Checked = true;
			}
			attributeEx = xmlHelper.GetAttributeEx("CableNum", "A");
			this.dataGridView.Rows[0].Cells[1].Value = attributeEx;
			attributeEx = xmlHelper.GetAttributeEx("StartNum", "B");
			this.dataGridView.Rows[1].Cells[1].Value = attributeEx;
			attributeEx = xmlHelper.GetAttributeEx("EndNum", "C");
			this.dataGridView.Rows[2].Cells[1].Value = attributeEx;
			attributeEx = xmlHelper.GetAttributeEx("CableModel", "D");
			this.dataGridView.Rows[3].Cells[1].Value = attributeEx;
			attributeEx = xmlHelper.GetAttributeEx("CableSpec", "E");
			this.dataGridView.Rows[4].Cells[1].Value = attributeEx;
			attributeEx = xmlHelper.GetAttributeEx("Length", "F");
			this.dataGridView.Rows[5].Cells[1].Value = attributeEx;
			attributeEx = xmlHelper.GetAttributeEx("LayPath", "G");
			this.dataGridView.Rows[6].Cells[1].Value = attributeEx;
			attributeEx = xmlHelper.GetAttributeEx("Remark", "H");
			this.dataGridView.Rows[7].Cells[1].Value = attributeEx;
		}

		private void SaveFormDataToXml()
		{
			if (this.rbAdd.Checked)
			{
				this.m_addDataMode = AddDataMode.Add_Ignore;
			}
			else if (this.rbCover.Checked)
			{
				this.m_addDataMode = AddDataMode.Add_Overwrite;
			}
			if (this.rbKeep.Checked)
			{
				this.m_addDataMode = AddDataMode.Add_SameRetain;
			}
			string text = string.Empty;
			for (int i = 0; i < this.clbCableCaterory.Items.Count; i++)
			{
				if (this.clbCableCaterory.GetItemChecked(i))
				{
					text = text + i.ToString() + ",";
				}
			}
			YArchitech.MEP.Electric.Common.XmlHelper xmlHelper = new YArchitech.MEP.Electric.Common.XmlHelper(CableLayCommon.GetUserDataFile(), "ElectricData");
			xmlHelper.SelectNode("CableListImportForm");
			xmlHelper.SetAttribute("ExcelPath", this.tbExcelPath.Text.Trim());
			xmlHelper.SetAttribute("SheetName", text.Trim());
			xmlHelper.SetAttribute("StartRow", this.tbStartRow.Text.Trim());
			string name = "Type";
			int addDataMode = (int)this.m_addDataMode;
			xmlHelper.SetAttribute(name, addDataMode.ToString());
			xmlHelper.SetAttribute("CableNum", this.dataGridView.Rows[0].Cells[1].Value.ToString());
			xmlHelper.SetAttribute("StartNum", this.dataGridView.Rows[1].Cells[1].Value.ToString());
			xmlHelper.SetAttribute("EndNum", this.dataGridView.Rows[2].Cells[1].Value.ToString());
			xmlHelper.SetAttribute("CableModel", this.dataGridView.Rows[3].Cells[1].Value.ToString());
			xmlHelper.SetAttribute("CableSpec", this.dataGridView.Rows[4].Cells[1].Value.ToString());
			xmlHelper.SetAttribute("Length", this.dataGridView.Rows[5].Cells[1].Value.ToString());
			xmlHelper.SetAttribute("LayPath", this.dataGridView.Rows[6].Cells[1].Value.ToString());
			xmlHelper.SetAttribute("Remark", this.dataGridView.Rows[7].Cells[1].Value.ToString());
			xmlHelper.SaveXml("");
		}

		private int ConvertAlphabetToInt(string alphabet)
		{
            //new byte[1];
			return (int)(Encoding.ASCII.GetBytes(alphabet)[0] - 65);
		}

		private string ReadExcelCell(Sheet sheet, int row, int col)
		{
			if (sheet == null)
			{
				return string.Empty;
			}
			string text = string.Empty;
			string result;
			try
			{
				CellType cellType = sheet.cellType(row, col);
				if (cellType == CellType.CELLTYPE_NUMBER)
				{
					text = sheet.readNum(row, col).ToString();
				}
				else if (cellType == CellType.CELLTYPE_STRING)
				{
					text = sheet.readStr(row, col);
				}
				else if (cellType == CellType.CELLTYPE_BOOLEAN)
				{
					text = sheet.readBool(row, col).ToString();
				}
				result = text;
			}
			catch (System.Exception)
			{
				result = string.Empty;
			}
			return result;
		}

		private void tbStartRow_Leave(object sender, EventArgs e)
		{
			try
			{
				if (int.Parse(this.tbStartRow.Text) < 0)
				{
					throw new System.Exception();
				}
			}
			catch
			{
				MessageBox.Show("起始行号不合法。");
				this.tbStartRow.Focus();
			}
		}

		private void CableListImportForm_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape)
			{
				base.Close();
			}
		}

		private ComboBox m_cmbSelectValue = new ComboBox();

		private int m_rowIndex;

		private int m_columnIndex;

		public AddDataMode m_addDataMode;

		private List<CableListField> m_fields;

		public List<CableListData> m_cableListData;

		private Book m_excelBook;

		private const string XmlNode_Root = "CableListImportForm";

		private const string XmlNode_ExcelPath = "ExcelPath";

		private const string XmlNode_SheetName = "SheetName";

		private const string XmlNode_Type = "Type";

		private const string XmlNode_StartRow = "StartRow";
	}
}
